/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package botobjects;

import interfaces.BotObject;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import main.UserCentral;

import org.apache.log4j.Logger;

import tools.StringTools;
import database.DBConnectionFactory;

/**
 * This class represents a bot administrator
 * 
 * 
 */
public class Admin implements BotObject {
   /**
    * Demotes the specified user from admin to regular user
    * 
    * @param args
    *           The main nick of the user to demote
    * @return true if the admin was successfully removed from the admin list
    */
   public static boolean deleteFromDB(final String... args) {
	  boolean out = false;
	  if (args.length < 1) // if there's no nick, we don't know who to delete
		 return out;
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT fullaccess FROM admins WHERE mainnick = ?");
		 ps.setString(1, args[0]);
		 rs = ps.executeQuery();
		 if (rs.next()) {
			if (!rs.getBoolean("fullaccess")) { // super admins have full access and cannot be demoted
			   ps = DBConnectionFactory.getConnectionHandler().getConnection()
					 .prepareStatement("DELETE FROM admins WHERE mainnick = ?");
			   ps.setString(1, args[0]);

			   if (ps.executeUpdate() == 1) {
				  UserCentral.getInstance().setOnlineUsersAdminStatus(args[0], false);
				  out = true;
			   }
			}
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Returns a list of all current admins
    * 
    * @return List containing Admin objects corresponding to all current admins
    */
   public static List<Admin> getAdmins() {
	  List<Admin> out = new LinkedList<Admin>();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("SELECT * FROM admins");
		 rs = ps.executeQuery();

		 while (rs.next()) {
			out.add(new Admin(rs.getString("mainnick"), rs.getBoolean("fullaccess")));
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   private String nick = "";

   private boolean superAdmin = false;

   public Admin(final String nick, final boolean superAdmin) {
	  this.nick = nick;
	  this.superAdmin = superAdmin;
   }

   @Override
   public List<String> getIRCOutput(final int outputType, final String... args) {
	  return new LinkedList<String>();
   }

   public String getNick() {
	  return nick;
   }

   @Override
   public Map<String, Object> getRPCOutput(final int... includes) {
	  Map<String, Object> out = new HashMap<String, Object>();
	  if (StringTools.isNullOrEmpty(getNick()))
		 return out;
	  out.put("Nick", getNick());
	  out.put("Super Admin", isSuperAdmin());
	  return out;
   }

   public boolean isSuperAdmin() {
	  return superAdmin;
   }

   @Override
   public boolean saveToDB() {
	  boolean out = false;
	  if (StringTools.isNullOrEmpty(getNick()))
		 return out;
	  PreparedStatement ps = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("INSERT INTO admins VALUES(?,?)");
		 ps.setString(1, getNick());
		 ps.setBoolean(2, isSuperAdmin());

		 if (ps.executeUpdate() == 1) {
			UserCentral.getInstance().setOnlineUsersAdminStatus(getNick(), true);
			out = true;
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   public void setNick(final String nick) {
	  this.nick = nick;
   }

   public void setSuperAdmin(final boolean isSuperAdmin) {
	  superAdmin = isSuperAdmin;
   }

}
